import 'dart:typed_data';

import 'package:example/datebase/text_data_dto.dart';
import 'package:example/datebase/text_icon_data.dart';
import 'package:example/led_view/vertical_led_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_custom_view/flutter_custom_view.dart';

import '../datebase/text12.dart';
import '../led_view/horizontal_led_screen.dart';
import '../led_view/led_view_widget.dart';

class PixelsViewPage extends StatefulWidget {
  @override
  _PixelsViewPageState createState() => _PixelsViewPageState();
}

class _PixelsViewPageState extends State<PixelsViewPage> {
  List<TextDataDTO> textList=[];
  late List<String> imageUrlList;
  TextEditingController? controller;
  Color externalColor = const Color(0xFFFF0000);
  Color textColor=Colors.white;
  bool isSelectedTextColor=false;
  String inputText = '';
  int mode = 0;
  int brightness = 20;
  int brightness2 = 20;
  int optity = 20;
  double canvasSizeHeight = 40;
  int dynamicMode=0;
  @override
  void initState() {
    controller = TextEditingController(text: "");
    imageUrlList = PixelsViewDao.getImageUrlList();
    super.initState();
  }

  getData(String str) async {
    Uint8List stringBytes = await Text12.getStringBytes(str);
    setState((){
      textList.add(TextDataDTO(
        color: Colors.redAccent.value,
        colorR: Colors.redAccent.red,
        colorG: Colors.redAccent.green,
        colorB: Colors.redAccent.blue,
        data:stringBytes,
        sendData:stringBytes,
        type: 0,
        widthCount:stringBytes.length~/2,
      ));
    });
  }

  void getImageByteList(int index) {
    List<Uint8List> list = TextIconData.getIconArray();
    Uint8List stringBytes= list[index];
    setState(() {
      textList.add(TextDataDTO(
        color: Colors.redAccent.value,
        colorR: Colors.redAccent.red,
        colorG: Colors.redAccent.green,
        colorB: Colors.redAccent.blue,
        data: stringBytes,
        sendData: stringBytes,
        type: 1,
        widthCount: stringBytes.length ~/ 2,
      ));
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        title: const Text("像素显示器",style: TextStyle(
          decorationThickness:0.0,
          decoration: TextDecoration.lineThrough,
        ),),
      ),
      body: Column(
        children: [
          Container(
              width: MediaQuery.of(context).size.width*2/3,
              // height: 100,
              decoration: BoxDecoration(
                border: Border.all(
                  width: 2,
                  color: Colors.cyanAccent,
                ),
                  borderRadius: BorderRadius.circular(4)
              ),
              child:  HorizontalLedScreen(
                key: ValueKey("${textList.map((e) => e.toString()).toList()} ${dynamicMode}"),
                textList: textList,
                textColor: HSVColor.fromColor(textColor).withValue(brightness2 / 100).toColor().withOpacity(optity/100),
                externalColor: HSVColor.fromColor(externalColor).withValue(brightness / 100).toColor(),
                isSelectedTextColor: isSelectedTextColor,
                mode: mode,
                dynamicMode: dynamicMode,
              )),
          const SizedBox(height: 10,),
          Container(
              // width: 100,
              height: MediaQuery.of(context).size.width*2/3,
              decoration: BoxDecoration(
                border: Border.all(
                  width: 2,
                  color: Colors.cyanAccent,
                ),
                borderRadius: BorderRadius.circular(4)
              ),
              child: VerticalLedScreen(
                key: ValueKey("${textList.map((e) => e.toString()).toList()} ${dynamicMode}"),
                textList: textList,
                textColor: HSVColor.fromColor(textColor).withValue(brightness2 / 100).toColor().withOpacity(optity/100),
                externalColor: HSVColor.fromColor(externalColor).withValue(brightness / 100).toColor(),
                isSelectedTextColor: isSelectedTextColor,
                mode: mode,
                dynamicMode: dynamicMode,
                isInvert: false,
              )),
          const SizedBox(height: 10,),
          Expanded(
            child: SingleChildScrollView(
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 0,vertical: 10),
                    alignment: Alignment.topCenter,
                    child: Column(
                      children: [
                        _getTextField(),
                        _changeDynamicMode(),
                        _changeGrient(),
                        Container(
                          height: 100,
                          width: MediaQuery.of(context).size.width,
                          margin: const EdgeInsets.symmetric(horizontal: 16,vertical: 10),
                          padding: const EdgeInsets.symmetric(horizontal: 16,vertical: 10),
                          alignment: Alignment.center,
                          color: Colors.white12,
                          child: GridView.builder(
                              itemCount: imageUrlList.length,
                              shrinkWrap: true,
                              physics: const BouncingScrollPhysics(),
                              scrollDirection: Axis.horizontal,
                              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 2,
                                mainAxisSpacing: 10,
                                crossAxisSpacing: 10,
                                childAspectRatio: 1,
                              ),
                              itemBuilder: (BuildContext context,int index){
                                return GestureDetector(
                                  onTap: (){
                                    setState((){
                                      // viewModelList.add(ViewModel(viewType: ViewType.image,imageUrl: imageUrlList[index]));
                                      getImageByteList(index);
                                    });
                                  },
                                  child: Container(
                                      child: Image.asset(imageUrlList[index],color:Colors.white,)
                                  ),
                                );
                              }),
                        ),
                        SizedBox(
                          height: 150,
                          child: RectangleColorPicker(
                            selectRadius: 16,
                            initialColor: externalColor,
                            aspectRatio: 4 / 7,
                            onCallBack: (
                                double h,
                                double s,
                                ) {
                              setState(() {
                                externalColor = HSVColor.fromAHSV(1.0, h, s, 1.0).toColor();
                              });
                            },
                            onCallBackEnd: (
                                double h,
                                double s,
                                ) {
                              setState(() {
                                externalColor = HSVColor.fromAHSV(1.0, h, s, 1.0).toColor();
                              });
                            },
                          ),
                        ),
                        AnimationSlider(
                          isSingle: true,
                          height: 50,
                          min: 1,
                          max: 100,
                          icon: const Icon(Icons.color_lens_outlined),
                          value: brightness.toDouble(),
                          onValueChange: (_value) {
                            setState(() {
                              brightness =_value.toInt();
                            });
                          },
                        ),
                        GestureDetector(
                          onTap: (){
                            setState((){
                              isSelectedTextColor = !isSelectedTextColor;
                            });
                          },
                          child: Container(
                            width: 200,
                              height: 80,
                              padding: EdgeInsets.symmetric(vertical: 10),
                              margin: EdgeInsets.symmetric(vertical: 10),
                              color: textColor,
                              alignment: Alignment.center,
                              child: Text("是否使用统一颜色: ${isSelectedTextColor}")),
                        ),
                        Container(
                          height: 100,
                          width: MediaQuery.of(context).size.width,
                          margin: const EdgeInsets.symmetric(horizontal: 16,vertical: 10),
                          padding: const EdgeInsets.symmetric(horizontal: 16,vertical: 10),
                          alignment: Alignment.center,
                          color: Colors.white12,
                          child: GridView.builder(
                              itemCount: imageUrlList.length,
                              shrinkWrap: true,
                              physics: const BouncingScrollPhysics(),
                              scrollDirection: Axis.horizontal,
                              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 2,
                                mainAxisSpacing: 10,
                                crossAxisSpacing: 10,
                                childAspectRatio: 1,
                              ),
                              itemBuilder: (BuildContext context,int index){
                                return GestureDetector(
                                  onTap: (){
                                    setState((){
                                      // viewModelList.add(ViewModel(viewType: ViewType.image,imageUrl: imageUrlList[index]));
                                      getImageByteList(index);
                                    });
                                  },
                                  child: SizedBox(
                                      width: 10,
                                      height: 10,
                                      child: Image.asset(imageUrlList[index],color:Colors.white,)
                                  ),
                                );
                              }),
                        ),
                        SizedBox(
                          height: 150,
                          child: RectangleColorPicker(
                            selectRadius: 16,
                            initialColor: textColor,
                            aspectRatio: 4 / 7,
                            onCallBack: (
                                double h,
                                double s,
                                ) {
                              setState(() {
                                textColor = HSVColor.fromAHSV(1.0, h, s, 1.0).toColor();
                              });
                            },
                            onCallBackEnd: (
                                double h,
                                double s,
                                ) {
                              setState(() {
                                textColor = HSVColor.fromAHSV(1.0, h, s, 1.0).toColor();
                              });
                            },
                          ),
                        ),
                        AnimationSlider(
                          isSingle: true,
                          height: 50,
                          min: 1,
                          max: 100,
                          icon: const Icon(Icons.color_lens_outlined),
                          value: brightness2.toDouble(),
                          onValueChange: (_value) {
                            setState(() {
                              brightness2 =_value.toInt();
                            });
                          },
                        ),
                        SizedBox(height: 10,),
                        AnimationSlider(
                          isSingle: true,
                          height: 50,
                          min: 1,
                          max: 100,
                          icon: const Icon(Icons.color_lens_outlined),
                          value: optity.toDouble(),
                          onValueChange: (_value) {
                            setState(() {
                              optity =_value.toInt();
                            });
                          },
                        ),
                      ],
                    )
                )
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {  },
        child: const Icon(Icons.scatter_plot),
      ),
    );
  }

  double getNumberBytesCharacters(String text,double height){
    Size size = boundingTextSize(text);
    double proportion = size.width/size.height;
    return height*proportion;
  }

  static Size boundingTextSize(String text,{int maxLines = 2^31, double maxWidth = double.infinity}) {
    if (text.isEmpty) {
      return Size.zero;
    }
    final TextPainter textPainter = TextPainter(
        textDirection: TextDirection.ltr,
        text: TextSpan(text: text, style: const TextStyle(fontWeight: FontWeight.bold,fontSize: 24)), maxLines: maxLines)
      ..layout(maxWidth: maxWidth);
    return textPainter.size;
  }

  SizedBox _getTextField() {
    BorderSide borderSide = const BorderSide(color: Colors.blue, width: 4);
    InputDecoration inputDecoration = InputDecoration(
      border: UnderlineInputBorder(borderSide: borderSide),
      disabledBorder: UnderlineInputBorder(borderSide: borderSide),
      enabledBorder: UnderlineInputBorder(borderSide: borderSide),
      focusedBorder: UnderlineInputBorder(borderSide: borderSide),
    );

    return SizedBox(
      child: Material(
        color: Colors.black54,
        child: Row(
          children: [
            Expanded(
              child: Container(
                height: 100,
                child: TextField(
                  enableSuggestions: false,
                  textAlign: TextAlign.center,
                  controller: controller,
                  style: const TextStyle(
                    color: Colors.yellow,
                    fontSize: 32,
                    fontFamily: "Monospace"
                  ),
                    decoration: inputDecoration,
                    onChanged: (val) {
                      setState(() {
                        inputText = val;
                        // controller?.clear();
                      });
                    },
                  //controller: _controller,
                ),
              ),
            ),
            const Spacer(),
            GestureDetector(
              onTap: (){
                List<String> string;
                inputText.length;
                setState((){
                  for(int i=0;i<inputText.length;i++){
                    getData(inputText[i]);
                  }
                });
              },
              child: Container(
                width: 50,
                height: 50,
                color: Colors.brown,
                alignment: Alignment.center,
                child: const Text("输入"),
              ),
            )
          ],
        )
      ),
    );
  }

  Widget _changeGrient() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        GestureDetector(
            onTap: (){
              setState((){
                mode = 0;
              });
            },
            child: Text("线性渐变",style: TextStyle(color: Colors.white,fontSize: 20),)),
        GestureDetector(
            onTap: (){
              setState((){
                mode = 1;
              });
            },child: Text("梯度渐变",style: TextStyle(color: Colors.white,fontSize: 20),)),
        GestureDetector(
            onTap: (){
              setState((){
                mode = 2;
              });
            },child: Text("扇形渐变",style: TextStyle(color: Colors.white,fontSize: 20),)),
      ],
    );
  }

  Widget _changeDynamicMode() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        GestureDetector(
            onTap: (){
              setState((){
                dynamicMode = 0;
              });
            },
            child: Text("固定",style: TextStyle(color: Colors.white,fontSize: 20),)),
        GestureDetector(
            onTap: (){
              setState((){
                dynamicMode = 1;
              });
            },child: Text("左移",style: TextStyle(color: Colors.white,fontSize: 20),)),
        GestureDetector(
            onTap: (){
              setState((){
                dynamicMode = 2;
              });
            },child: Text("右移",style: TextStyle(color: Colors.white,fontSize: 20),)),
        GestureDetector(
            onTap: (){
              setState((){
                dynamicMode = 3;
              });
            },child: Text("闪烁",style: TextStyle(color: Colors.white,fontSize: 20),)),
        GestureDetector(
            onTap: (){
              setState((){
                textList.removeAt(textList.length-1);
              });
            },child: Text("删除",style: TextStyle(color: Colors.white,fontSize: 20),)),
        GestureDetector(
            onTap: (){
              setState((){
                textList = [];
              });
            },child: Text("清空",style: TextStyle(color: Colors.white,fontSize: 20),)),
      ],
    );
  }

}
